# HarmonyOS应用简化部署脚本（仅使用已有HAP包）
# 使用前请确保hdc已连接设备

# 应用包名
$BUNDLE_NAME = "com.example.work0907"
# 已构建的HAP包路径
$ENTRY_HAP = "entry\build\default\outputs\default\entry-default-unsigned.hap"
# 临时目录名（使用随机字符串避免冲突）
$TMP_DIR = "hm_deploy_tmp_" + [System.Guid]::NewGuid().ToString("N").Substring(0, 16)

# 设置错误时停止执行
$ErrorActionPreference = "Stop"

try {
    Write-Host "1. 检查HAP包是否存在..." -ForegroundColor Green
    if (-Not (Test-Path $ENTRY_HAP)) {
        throw "HAP包不存在: $ENTRY_HAP"
    }
    Write-Host "  ✓ HAP包已找到"

    Write-Host "2. 停止正在运行的应用..." -ForegroundColor Green
    try {
        hdc shell aa force-stop "$BUNDLE_NAME"
        Write-Host "  ✓ 应用已停止"
    } catch {
        Write-Host "  ○ 应用未运行或停止失败，继续执行..." -ForegroundColor Yellow
    }

    Write-Host "3. 创建设备临时目录..." -ForegroundColor Green
    hdc shell mkdir -p "data/local/tmp/$TMP_DIR"
    Write-Host "  ✓ 临时目录已创建"

    Write-Host "4. 传输HAP包到设备..." -ForegroundColor Green
    hdc file send "$ENTRY_HAP" "data/local/tmp/$TMP_DIR/entry-default-unsigned.hap"
    Write-Host "  ✓ HAP包已传输"

    Write-Host "5. 安装应用包..." -ForegroundColor Green
    hdc shell bm install -p "data/local/tmp/$TMP_DIR"
    Write-Host "  ✓ 应用已安装"

    Write-Host "6. 清理设备临时文件..." -ForegroundColor Green
    hdc shell rm -rf "data/local/tmp/$TMP_DIR"
    Write-Host "  ✓ 临时文件已清理"

    Write-Host "7. 启动应用..." -ForegroundColor Green
    hdc shell aa start -a EntryAbility -b "$BUNDLE_NAME" -m entry
    Write-Host "  ✓ 应用已启动"

    Write-Host "✅ 部署完成！应用已成功启动" -ForegroundColor Green

} catch {
    Write-Host "❌ 部署失败: $($_.Exception.Message)" -ForegroundColor Red
    Write-Host "请检查错误信息并重试，确保hdc已正确连接设备" -ForegroundColor Red
    exit 1
}